package org.apache.rocketmq.example.kang.product.cluster;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

/**
 * 同一机器向不同集群发送信息
 */
public class ProducerUnitNameDemo {

    public static void main(String[] args) throws Exception{

        Integer port  = 9876;
        String localIp = "192.168.11.62";
        String localIpNamessrvAddr = localIp + ":" + port;

        String remoteIp = "192.168.25.128";
        String remoteIpNamessrvAddr = remoteIp + ":" + port;

        String commonProducerGroup = "kang2_test_producer_group";
        String commonTopic = "kang2_test";

        //　创建第一个生产者
        DefaultMQProducer producer = new DefaultMQProducer(commonProducerGroup+"1");
        producer.setNamesrvAddr(localIpNamessrvAddr);
        producer.setUnitName("DefaultClusterb1");
        producer.start();
        // 打印一些客户端信息（虽然不是直接的ClientID，但可能是有用的信息）
        // System.out.println("Client ID (indirectly): " + producer.buildMQClientId());


        //　创建第二个生产者
        DefaultMQProducer producer2 = new DefaultMQProducer(commonProducerGroup+"2");
        producer2.setNamesrvAddr(remoteIpNamessrvAddr);
        // 不指定unitName会导致 MQClientException: No route info of this topic: dw_test_02
        producer2.setUnitName("DefaultClusterb2");
        producer2.start();
        try {
            //　向第一个 RocketMQ 集群发送消息
            SendResult result1 = producer.send(
                    new Message(commonTopic+"1" ,
                            ("hello "+localIp+" nameserver").getBytes()));
            System.out.printf("%s%n", result1);

        } catch (Throwable e) {
            System.out.println("-----first------------");
            e.printStackTrace();
            System.out.println("-----first------------");
        }


        try {
            //　向第二个 RocketMQ 集群发送消息
            SendResult result2 = producer2.send(
                    new Message(commonTopic+"2" ,
                            ("hello "+remoteIp+" nameserver").getBytes()));
            System.out.printf("%s%n", result2);
        } catch (Throwable e) {
            System.out.println("-----secornd------------");
            e.printStackTrace();
            System.out.println("-----secornd------------");
        }
        //睡眠 10s，简单延迟该任务的结束
        Thread.sleep(10000);
    }
}
